<script setup lang="ts">
import { PlusDialogForm, PlusDrawerForm } from "plus-pro-components";
import { Column, ModelFormOpts } from "../type";
import { computed, ref } from "vue";

type ModelFormViewProps = { modelValue?: any; ui?: ModelFormOpts };

// 组件属性
const props = withDefaults(defineProps<ModelFormViewProps>(), {});

// 组件emit事件
const emit = defineEmits(["update:modelValue", "onSubmit"]);
const key = ref<string>("");
// 组件事件类型标记
const symbol = ref();

const option = computed<ModelFormOpts>(() => {
  return uiOption.value || {};
});

const title = computed(() => {
  return option.value.title || "";
});

const uiOption = ref<any>(props.ui);
const columns = computed(() => uiOption.value?.columns || []);
const component = computed(() =>
  uiOption.value?.viewType === "drawer" ? PlusDrawerForm : PlusDialogForm
);

// 页面内实例数据
const _data = ref(props.modelValue || {});
const value = computed({
  get: () => _data.value,
  set: value => {
    _data.value = value;
    emit("update:modelValue", value);
  }
});

// 编辑表单弹窗显示
const visible = ref<boolean>(false);

// 编辑表单弹窗显示
const open = (data: any, symb: string, opts?: ModelFormOpts) => {
  symbol.value = symb;
  _data.value = data;
  if (opts) {
    uiOption.value = opts;
    key.value = Math.random().toString(36).slice(2);
  }
  visible.value = true;
};

// 编辑表单弹窗隐藏
const hide = () => {
  visible.value = false;
};

// 编辑表单提交
const submit = () => {
  emit("update:modelValue", value.value);
  emit("onSubmit", value.value, symbol.value);
  hide();
};

defineExpose({
  open,
  hide,
  data: () => value.value
});
</script>

<template>
  <component
    :is="component"
    :key="key"
    v-model="visible"
    v-model="value"
    :title="title"
    :form="option"
    @confirm="submit"
    @cancel="hide"
  >
    <template v-for="slot in Object.keys($slots)" #[slot]="scope">
      <slot :name="slot" v-bind="scope" />
    </template>
  </component>
</template>
<style lang="scss" scoped></style>
